<?php include_once ('function/check_login_function.php');
	  include_once ('function/check_oauth_function.php');
	  include_once ('function/date_conversion_function.php');
	  onlyValid();?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Health Tracker</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="Health Tracker">
    <meta name="author" content="">

    <!-- Le styles -->
    <link href="css/bootstrap.css" rel="stylesheet">
    <style>
      body {
        padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
      }
	  
	  #loading {
		position: absolute;
		top: 5px;
		right: 5px;
	  }

	  #calendar {
		width: 900px;
		margin: 0 auto;
	  }
    </style>
    <link href="css/bootstrap-responsive.css" rel="stylesheet">
	<link rel='stylesheet' type='text/css' href='css/fullcalendar.css' />
	<link rel='stylesheet' type='text/css' href='css/fullcalendar.print.css' media='print' />
	<link rel='stylesheet' type='text/css' href='css/jquery.ui.timepicker.css'/>
	<link rel='stylesheet' type='text/css' href='css/smoothness/jquery-ui-1.8.21.custom.css' />
	<link rel='stylesheet' type='text/css' href='css/style.css' media='print' />
	<link rel='stylesheet' type='text/css' href='css/customstyles.css' media='print' />
    <link rel="shortcut icon" href="ico/favicon.ico">
    <link rel="apple-touch-icon-precomposed" sizes="144x144" href="ico/apple-touch-icon-144-precomposed.png">
    <link rel="apple-touch-icon-precomposed" sizes="114x114" href="ico/apple-touch-icon-114-precomposed.png">
    <link rel="apple-touch-icon-precomposed" sizes="72x72" href="ico/apple-touch-icon-72-precomposed.png">
    <link rel="apple-touch-icon-precomposed" href="ico/apple-touch-icon-57-precomposed.png">
	
  </head>

  <body>
  <?php
  include_once('nav.php');
  ?>
      
    <div class="container">
    <div class="row">
    <div class="span8">
      <h1 style="padding-left: 20px;">Calendar</h1>
		<?php
			if ($client->getAccessToken()) {
			
			} else {
			  $authUrl = $client->createAuthUrl();
			  print "<a class='alert alert-success' style='font-size:x-large;margin:20px;' href='$authUrl'>Connect Me!</a>";
			}
		?>
		<br /><br />
		<div id= "error_message" class="alert alert-error" style="margin-top:-45px;margin-left:30px;margin-bottom:5px;width:825px;padding-left:30px;text-align:centre;"></div>
		<div id='loading' style='display:none;padding-left:30px;'>loading...</div>
		<div id='calendar' style="padding-left: 30px;"></div>
		
		<div id='dialog-message' style='display:none;'>
			<form>
			<div style="text-align:right;">
				<label for="edited_title">Title:</label> <input type="text" id="edited_title" style="width: 205px;" tabindex="1">
				
				<div>
					<label for="note">Note:</label>
					<textarea cols="20" rows="3" id="note" tabindex="2"></textarea>
				</div><br />
                
				
				<div style="margin-bottom: 5px;">
					<span id="wholeday_label_id">All day</span>:<input type="checkbox" id="allday_checkbox" tabindex-"3">
				</div>

				<?php if (SHOW_DATE_SELECTION == true){ ?>
				<div style="margin-bottom: 5px;">
					<span style="float:right;">
						<span id="month_label_id">Date</span>: <input type="text" id="datepicker_startdate" style="width: 90px;" tabindex="4">
					 	<input type="text" id="datepicker_enddate" style="width: 90px;margin-bottom:4px;" tabindex="5">
					</span>
				</div>
				<?php } ?>

				<div style="margin-bottom: 5px;">
						<span style="float:right;">
						<span id="time_label_id">Time</span>: <input type="text" id="timepicker_starttime" style="width: 90px;">
						<input type="text" id="timepicker_endtime" style="width: 90px;margin-bottom:4px;">
						</span>
				</div>
                <br style= "clear:right;" />
                <?php if (SHOW_COLOR_SELECTION == true){ ?>
				<div style="margin-bottom: 5px;">
					<span id="ColorPicker1"></span>
					<br /><br />
					<span id="ColorSelectionTarget1">&nbsp;</span>
				</div>
                <?php } ?>
			</div>
		</form>
		</div>
	</div>
    </div>
    </div>
    </div> <!-- /container -->
			<!--<script src="js/jquery.js"></script>-->
    <script src="js/bootstrap.js"></script>
	<script src='js/calendar_config.js'></script>
	<script src='js/jquery-1.7.2.min.js'></script>
	<script src='js/jquery-ui-1.8.21.custom.min.js'></script>
	<script src='js/fullcalendar.min.js'></script>
	<script src='js/langEN.js'></script>
	<script src='js/dateformat.js'></script>
	<script src='js/simple_colorpicker.js'></script>
	<script src='js/jquery-ui-timepicker-0.2.9/jquery.ui.timepicker.js'></script>
	<script type='text/javascript'>
	var Calendar = {};
	Calendar.defaultEventColor = Config.defaultEventColor;

	$(document).ready(function() {
	$('#error_message').hide();

	var applyToObject = function(event, result) {
		event.start 		= result.start;
		event.end 			= result.end;
		event._start 		= result.start;
		event._end 			= result.end;
		event._id 			= result.id;
		event.time_start	= result.time_start;
		event.time_end  	= result.time_end;
		event.color		  	= result.color;
		event.allDay		= result.allDay;
		event.desc			= result.desc;

    return event;
	};
	// Timepicker Starttime
	$('#timepicker_starttime').timepicker({
		showPeriodLabels: false,
		hourText: Lang.Popup.TimepickerHourtext,
		minuteText: Lang.Popup.TimepickerMinutetext,
		showCloseButton: true,// shows an OK button to confirm the edit
		closeButtonText: Lang.Popup.TimepickercloseButtonText,// Text for the confirmation button (ok button)
		showNowButton: true,// Shows the 'now' button
		nowButtonText: Lang.Popup.TimepickernowButtonText,
		hours: {
			starts: Config.Popup.timePickerMinHour,
			ends: Config.Popup.timePickerMaxHour
		},
		minutes: {
			starts: 0,// First displayed minute
			ends: 59,// Last displayed minute
			interval: Config.Popup.timePickerMinuteInterval// Interval of displayed minutes
		}
	});
	// Timepicker Endtime		
	$('#timepicker_endtime').timepicker({
		showPeriodLabels: false,
		hourText: Lang.Popup.TimepickerHourtext,
		minuteText: Lang.Popup.TimepickerMinutetext,
		showCloseButton: true,// shows an OK button to confirm the edit
		closeButtonText: Lang.Popup.TimepickercloseButtonText,// Text for the confirmation button (ok button)
		showNowButton: true,// Shows the 'now' button
		nowButtonText: Lang.Popup.TimepickernowButtonText,
		hours: {
		  starts: Config.Popup.timePickerMinHour,// First displayed hour
		  ends: Config.Popup.timePickerMaxHour// Last displayed hour
		},
		minutes: {
		  starts: 0,// First displayed minute
		  ends: 59,// Last displayed minute
		  interval: Config.Popup.timePickerMinuteInterval// Interval of displayed minutes
		}
	});
	// Datepicker startdate
	$('#datepicker_startdate').datepicker({
		dateFormat: 'dd/mm/yy'
	});
	// Datepicker enddate
	$('#datepicker_enddate').datepicker({
		dateFormat: 'dd/mm/yy'
	});
	// Colorpicker
	$('#ColorPicker1').empty().addColorPicker({
		clickCallback: function(elem,c) {
			$('#ColorSelectionTarget1').css('background-color',c);
			Calendar.defaultEventColor = elem.attr('color');
		}
	});
	$('#ColorSelectionTarget1').css('background-color',Calendar.defaultEventColor);
	//#########################
	var disableTimeCombos = function() {
		$('#timepicker_starttime').attr('disabled', 'disabled');
		$('#timepicker_endtime').attr('disabled', 'disabled');
	};
	var enableTimeCombos = function() {
		$('#timepicker_starttime').removeAttr('disabled');
		$('#timepicker_endtime').removeAttr('disabled');
	};
	$('#allday_checkbox').click(function(t){
		if(t.currentTarget.checked == false) {
			$('#timepicker_starttime').removeAttr('disabled');
			$('#timepicker_endtime').removeAttr('disabled');
		}else{
			$('#timepicker_starttime').attr('disabled', 'disabled');
			$('#timepicker_endtime').attr('disabled', 'disabled');
		}
	});
	//#########################
		
		
	// START Add new Event (click on empty Date Field)		
	var addEvent = function(start, end, note) {
		$('#error_message').hide();
		var title = $('#edited_title')[0].value;
		var note = $('#note')[0].value;
		if (title) {
			// is a date selected in the datepickers, then use those dates
			var dp_startdate 	= $('#datepicker_startdate').datepicker('getDate');
			var dp_enddate 		= $('#datepicker_enddate').datepicker('getDate');

			if(dp_startdate !== null && dp_enddate !== null) {
				start = dp_startdate;
				end = dp_enddate;
			}
				
			if($('#allday_checkbox').is(':checked')) {
				var startdate = (start.format('mm/dd/yyyy') + ' 00:00:00');
				var enddate = (end.format('mm/dd/yyyy') + ' 23:59:59');
			}else{
				var startdate 	  = (start.format('mm/dd/yyyy')+ ' ' + $('#timepicker_starttime')[0].value + ':00');
				var enddate 	  = (end.format('mm/dd/yyyy')+ ' ' + $('#timepicker_endtime')[0].value + ':00');
			}
			var note
			//Add event to google calendar
			if(startdate <= enddate  && dp_startdate !== null && dp_enddate !== null) {
				var dataString = 'title='+ title +'&note='+ note +'&date_start='+ startdate +'&date_end='+ enddate + '&color=' + Calendar.defaultEventColor;
				$.ajax({
				type:"POST",
			    url:"function/calendar_function.php?action=add",
			    data: dataString
				});
				$('#calendar').fullCalendar('refetchEvents');
			}else{
				$('#error_message').html(Lang.Alert.TimesNotCorrect);			    
				$('#error_message').show();
			}
		}
	};
	// END Add new Event (click on empty Date Field)

	// START Update existing Event (click on existing Event and made some Changes)
	var updateEvent = function(event) {
		$('#error_message').hide();
		
		var title = $('#edited_title')[0].value;
		//check whether the title are null or empty
		if(title != null && title != '') {
			event.title = title;
			var note = $('#note')[0].value;
			event.desc = note;
        
			// is a date selected in the datepickers, then use those dates
			var dp_startdate 	= $('#datepicker_startdate').datepicker('getDate');
			var dp_enddate 		= $('#datepicker_enddate').datepicker('getDate');

			if(dp_startdate !== null && dp_enddate !== null) {
				event.start = dp_startdate;
				event.end = dp_enddate;
			}
				
			if($('#allday_checkbox').is(':checked')) {
				var startdate = (event.start.format('mm/dd/yyyy')+ ' 00:00:00');
				var enddate = (event.end.format('mm/dd/yyyy')+ ' 23:59:59');
				event.allDay = 1;
			}else{
				var startdate 	= (event.start.format('mm/dd/yyyy')+ ' ' + $('#timepicker_starttime')[0].value + ':00');
				var enddate 	= (event.end.format('mm/dd/yyyy')+ ' ' + $('#timepicker_endtime')[0].value + ':00');
				event.allDay = 0;
			}

			if(startdate <= enddate && dp_startdate !== null && dp_enddate !== null ) {
				// update to Google calendar
				var dataString = 'event_id='+ event.id + '&allDay=' + event.allDay  + '&title='+ event.title +'&note='+event.desc+ '&date_start='+startdate+'&date_end='+enddate+ '&color=' + Calendar.defaultEventColor;
				$.ajax({
				type:"POST",
			    url:"function/calendar_function.php?action=update",
			    data: dataString
				});

			  $('#calendar').fullCalendar('refetchEvents');
			  return true;
			}else{
				$('#error_message').html(Lang.Alert.TimesNotCorrect);			    
				$('#error_message').show();
			  return false;
			}
    }
	};
	// END Update existing Event (click on existing Event and made some Changes)

	// START update existing Event when User moved it (drag'n'drop)
	var onEventDropEvent = function(event) {
		$('#error_message').hide();
		var startdate 	= event.start.format('mm/dd/yyyy') + ' ' + event.time_start;
		if(event.end === null) {
	    var enddate = startdate;
	  }else{
	    var enddate 	= event.end.format('mm/dd/yyyy') + ' ' + event.time_end;
	  }
    event.allDay = event.allDay ? 1 : 0;

    // Update to Google calendar
		var dataString = 'event_id='+ event.id + '&color=' + event.color + '&allDay=' + event.allDay +'&title='+ event.title+'&note='+event.desc+'&date_start='+startdate+'&date_end='+enddate;
    $.ajax({
	   type:"POST",
	   url:"function/calendar_function.php?action=update",
	   data: dataString
			});
	};
	// END update existing Event when User moved it (drag'n'drop)		
	
	//User select on calendar space
	var onSelectEvent = function(start, end, allDay) {
		$('#error_message').hide();
		$('#dialog:ui-dialog').dialog( "destroy" );
		$('#edited_title')[0].value = '';
		$('#datepicker_startdate').datepicker('setDate', start); 
		$('#datepicker_enddate').datepicker('setDate', end);
		// default
		$('#allday_checkbox').attr('checked', true);

		$('#wholeday_label_id').html(Lang.Popup.allDayLabel);
		$('#month_label_id').html(Lang.Popup.MonthLabel );
		$('#time_label_id').html(Lang.Popup.TimeLabel );
		
		$('#calendar').fullCalendar('unselect');
		//disable the timepicer
		disableTimeCombos();
			
		var curr_hour = start.getHours();
		var curr_min = start.getMinutes();

		if(curr_hour == 0 && curr_min == 0) {
		var now = new Date();
			$('#timepicker_starttime')[0].value = dateFormat(now,'HH:00');
			$('#timepicker_endtime')[0].value	= dateFormat(now,'HH:00');
		}else{
			$('#timepicker_starttime')[0].value = dateFormat(start,'HH:MM');
			$('#timepicker_endtime')[0].value 	= dateFormat(end,'HH:MM');
		}

		$('#dialog-message').dialog({
			modal: true,
			title: Lang.Popup.Title,
			height: 400,
			width: 305,
			buttons: [{
			  text: Lang.Popup.saveButtonText,
			  click: function (a,b) {
			    var title = $('#edited_title')[0].value;
					//check if title are null or empty
					 if(title != null && title != '') {
						$( this ).dialog( "close" );
						//if title are not empty or null add the event to google calendar
						addEvent(start, end);
					 }else{
					  $('#error_message').html(Lang.Alert.EventTitleRequired);			    
					  $('#error_message').show();						
					}
			  }
			},
			{
			  text: Lang.Popup.closeButtonText,
			  click: function () {
			    $( this ).dialog( "close" );
			  }
			}]
		});
	};
	
	//user mouse over an event
	var onMouseoverEvent = function(me, event) {
		if(event.editable) {
			/*
			*	SHOW DELETE ICON, ALSO POSSIBLE TO SHOW AN EDIT ICON HERE
			*/
			var layer =	'<div id="events-layer" class="fc-transparent" style="position:absolute; width:100%; height:100%; top:-1px; text-align:right; z-index:100">'
			+ '<a><img src="images/delete.png" title="delete" width="14" id="delbut'+event.id+'" border="0" style="padding-right:5px; padding-top:2px;" /></a>'
			+ '</div>';

			me.append(layer);
			$('#delbut'+event.id).hide();
			$('#delbut'+event.id).fadeIn(200);
			$('#delbut'+event.id).click(function() {
				if(event.id) {
					//Update to google calendar
					var dataString = 'event_id='+ event.id ;
					$.ajax({
						type:"POST",
						url:"function/calendar_function.php?action=del",
						data: dataString
					});
					$('#calendar').fullCalendar('removeEvents', event.id);
				}
			});
		}
	};

	//user click on the event to update
	var onClickEvent = function(event) {
		$('#error_message').hide();
		if(!event.editable) {
			$('#error_message').html(Lang.Alert.NotAllowedToEdit);			    
			$('#error_message').show();			
		}else{
			var startdate = event.start;
			if(event.end === null) {
				var enddate = startdate;
			}else{
				var enddate = event.end
			}
	            
		  $( "#dialog:ui-dialog" ).dialog( "destroy" );
		  $('#edited_title')[0].value = event.title;
		  
		  $('#note')[0].value = event.desc;

		  $( "#datepicker_startdate" ).datepicker('setDate', dateFormat(Date.parse(startdate),'dd/mm/yy')); // or dateFormat(event._start,'dd/mm/yyyy')
		  $( "#datepicker_enddate" ).datepicker('setDate', dateFormat(Date.parse(enddate),'dd/mm/yy'));

		  $('#timepicker_starttime')[0].value = event.time_start.substring(0,5);
		  $('#timepicker_endtime')[0].value = event.time_end.substring(0,5);

		  if(event.allDay ) {
				$('#allday_checkbox').attr('checked', true);
				disableTimeCombos();
			}else{
				$('#allday_checkbox').attr('checked', false);
				enableTimeCombos();
			}
		if(event.color === '') {
				event.color = Calendar.defaultEventColor;
			}
			$('#ColorSelectionTarget1').css('background-color',event.color);
			Calendar.defaultEventColor = event.color;

			$( "#dialog-message" ).dialog({
				modal: true,
				title: Lang.Popup.EditEvent,
				height: 400,
				width: 305,
				buttons: [{
					text: Lang.Popup.updateButtonText,
					click: function () {
				    var title = $('#edited_title')[0].value;	    
						if(title != null && title != '') {
							var bln_correct = updateEvent(event);
								if(bln_correct) {
								$( this ).dialog( "close" );
								$('#error_message').html('');
							}
						}else{
							$('#error_message').html(Lang.Alert.EventTitleRequired);			    
							$('#error_message').show();
						}
					}
				},
				{
					text: Lang.Popup.closeButtonText,
					click: function () {
						$( this ).dialog( "close" );
					}
				}]
			});
			
			$('#wholeday_label_id').html(Lang.Popup.allDayLabel);
			$('#month_label_id').html(Lang.Popup.MonthLabel );
			$('#time_label_id').html(Lang.Popup.TimeLabel );
		}
	};

		/* initialize the external events
		-----------------------------------------------------------------*/

		$('#external-events div.external-event').each(function() {

			// create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/)
			// it doesn't need to have a start or end
			var eventObject = {
				title: $.trim($(this).text()) // use the element's text as the event title
			};

			// store the Event Object in the DOM element so we can get to it later
			$(this).data('eventObject', eventObject);

			// make the event draggable using jQuery UI
			$(this).draggable({
				zIndex: 999,
				revert: true,      // will cause the event to go back to its
				revertDuration: 0  //  original position after the drag
			});

		});

		/* initialize the calendar
		-----------------------------------------------------------------*/

		$('#calendar').fullCalendar({
			header: {
				left: 'prev,next today',
				center: 'title',
				right: 'month,agendaWeek,agendaDay'
			},
			theme : true,
			editable: true,
			selectable: true,
			timeFormat: 'H:mm{ - H:mm} ',
			axisFormat: 'H:mm',
			monthNames: 		Lang.Fullcalendar.monthNames,
			monthNamesShort: 	Lang.Fullcalendar.monthNamesShort,
			dayNames: 			Lang.Fullcalendar.dayNames,
			dayNamesShort: 		Lang.Fullcalendar.dayNamesShort,
			buttonText: {
				prev: '&nbsp;&#9668;&nbsp;',
				next: '&nbsp;&#9658;&nbsp;',
				today: 			Lang.Fullcalendar.buttonText.today,
				month: 			Lang.Fullcalendar.buttonText.month,
				week: 			Lang.Fullcalendar.buttonText.week,
				day: 			Lang.Fullcalendar.buttonText.day
			},
			droppable: true, // this allows things to be dropped onto the calendar !!!
			drop: function(date, allDay) { // this function is called when something is dropped

				// retrieve the dropped element's stored Event Object
				var originalEventObject = $(this).data('eventObject');

				// we need to copy it, so that multiple events don't have a reference to the same object
				var copiedEventObject = $.extend({}, originalEventObject);

				// assign it the date that was reported
				copiedEventObject.start = Date.parse(date) / 1000;
				copiedEventObject.allDay = allDay;

				if(copiedEventObject.title === undefined) {
					return false;
				}
			    // Add to Google calendar
				var dataString = 'title='+ copiedEventObject.title +'&date_start='+copiedEventObject.start;
	            $.ajax({
					type:"POST",
					url:"command/cal_events.php?action=add",
					data: dataString,
					success:function(result){
						result.event._id = result.event.id;
					}
		        });
						$('#calendar').fullCalendar('refetchEvents');		        

				// is the "remove after drop" checkbox checked?
				if ($('#drop-remove').is(':checked')) {
					// if so, remove the element from the "Draggable Events" list
					$(this).remove();
				}

			},
			//source of the event
			events: "function/calendar_function.php?action=get",
			
			eventDrop: function(event, delta) {
				onEventDropEvent(event);
			},
	        selectHelper: true,
			select: function(start, end, allDay) {
				onSelectEvent(start, end, allDay);
			},
	        loading: function(bool) {
	            if (bool) {
	            	$('#loading').show();
	            } else {
	            	$('#loading').hide();
	            }
	        },
	        eventMouseover: function(event, jsEvent, view) {
				onMouseoverEvent($(this), event);
			},
			eventMouseout: function(calEvent, domEvent) {
				$("#events-layer").remove();
			},
	        eventClick: function(event, element) {
				onClickEvent(event);
			},
		    allDayDefault: false
		});
});

	</script>
  </body>
</html>